package top.hudk.type;

import top.hudk.annotation.Valuation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 作用：
 *
 * @author hudk
 * @date 2020/4/7 17:04
 */
public class TypeUtils<T> {


    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

    public void testType() throws Exception {
        System.out.println(t.getClass().getName());
        Field[] fields = getAllFields(t.getClass());
        for (Field field : fields){
            Valuation valuation = field.getAnnotation(Valuation.class);
            System.out.println(getSql(valuation));
        }
    }

    private String getSql(Valuation valuation) throws Exception {
        if(valuation == null){
            return "000";
        }
        String table = valuation.table();
        String relation = valuation.relation();
        Field relationField = t.getClass().getDeclaredField(relation);
        relationField.setAccessible(true);
        Integer value = (Integer)relationField.get(t);
        System.out.println("value:"+value);
        String column = valuation.column();
        String sql = "select " + column + " from " + table + " where id =" + value;
        return sql;
    }

    /**
     * 获取本类及其父类的属性的方法
     * @param clazz 当前类对象
     * @return 字段数组
     */
    private static Field[] getAllFields(Class<?> clazz) {
        List<Field> fieldList = new ArrayList();
        while (clazz != null){
            fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        return fieldList.toArray(fields);
    }
//
//    private Class getGenericType(Class declaredClass) {
//        ParameterizedType parameterizedType = (ParameterizedType) declaredClass.getGenericSuperclass();
//        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
//        return (Class) actualTypeArguments[0];
//    }
}
